package com.leyou.privilege.service.impl;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.privilege.config.PasswordConfig;
import com.leyou.privilege.dto.ApplicationDTO;
import com.leyou.privilege.entity.Application;
import com.leyou.privilege.mapper.ApplicationMapper;
import com.leyou.privilege.service.ApplicationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: wangzibeng
 * Date: 2019/5/16 0016
 * Time: 11:58
 */

@Service
public class ApplicationServiceImpl implements ApplicationService {
    @Autowired
    private ApplicationMapper applicationMapper;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public void saveApplication(ApplicationDTO applicationDTO) {
        Application application = BeanHelper.copyProperties(applicationDTO, Application.class);
        // 设置服务密钥
        application.setSecret(passwordEncoder.encode(application.getSecret()));
        int insert = applicationMapper.insertSelective(application);
        if (insert != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
        // 新增服务权限信息
        List<Long> targetIdList = applicationDTO.getTargetIdList();
        int count = applicationMapper.insertApplicationPrivilege(application.getId(), targetIdList);
        if (count != targetIdList.size()) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    @Override
    public ApplicationDTO queryApplicationByIdAndSecret(Long id, String secret) {
        Application application = applicationMapper.selectByPrimaryKey(id);
        if (application == null) {
            throw new LyException(ExceptionEnum.APPLICATION_NOT_FOUND);
        }
        if (!passwordEncoder.matches(secret, application.getSecret())) {
            throw new LyException(ExceptionEnum.INVALID_SERVER_ID_SECRET);
        }
        //查询权限的id集合
        List<Long> ids = applicationMapper.queryTargetIdListByAppId(id);
        ApplicationDTO applicationDTO = BeanHelper.copyProperties(application, ApplicationDTO.class);
        applicationDTO.setTargetIdList(ids);
        return applicationDTO;
    }
}
